<template>
  <div class="server-list-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="服务器列表"
      fixed
      placeholder
      :border="false"
    >
      <template #right>
        <van-icon name="plus" size="20" @click="showAddDialog = true" />
      </template>
    </van-nav-bar>

    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="content-wrapper">
        <!-- 统计卡片 -->
        <div class="stats-card">
          <div class="stat-item">
            <van-icon name="cluster-o" class="stat-icon" />
            <div class="stat-info">
              <div class="stat-value">{{ servers.length }}</div>
              <div class="stat-label">服务器总数</div>
            </div>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <van-icon name="clock-o" class="stat-icon" />
            <div class="stat-info">
              <div class="stat-value">{{ expiringSoon }}</div>
              <div class="stat-label">即将到期</div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <van-empty
          v-if="servers.length === 0 && !loading"
          description="暂无服务器"
          image="search"
        >
          <van-button
            round
            type="primary"
            @click="showAddDialog = true"
          >
            添加服务器
          </van-button>
        </van-empty>

        <!-- 服务器卡片列表 -->
        <div v-else class="server-cards">
          <div
            v-for="server in servers"
            :key="server.id"
            class="server-card"
            @click="goToTerminal(server)"
          >
            <!-- 卡片头部 -->
            <div class="card-header">
              <div class="server-info">
                <h3 class="server-name">{{ server.name }}</h3>
                <p class="server-host">{{ server.host }}:{{ server.port }}</p>
              </div>
              <van-tag
                v-if="server.group_name"
                type="primary"
                plain
                size="medium"
              >
                {{ server.group_name }}
              </van-tag>
            </div>

            <!-- 服务器信息 -->
            <div class="server-meta">
              <div class="meta-item">
                <van-icon name="desktop-o" />
                <span>{{ server.username }}@{{ server.host }}</span>
              </div>
              <div class="meta-item" v-if="server.group_name">
                <van-icon name="cluster-o" />
                <span>{{ server.group_name }}</span>
              </div>
            </div>

            <!-- 到期时间 -->
            <div v-if="server.expire_date" class="expire-info" :class="getExpireClass(server.expire_date)">
              <van-icon name="clock-o" />
              <span>{{ formatExpireDate(server.expire_date) }}</span>
            </div>

            <!-- 卡片底部操作 -->
            <div class="card-footer">
              <van-button
                plain
                size="small"
                type="primary"
                icon="desktop-o"
                @click.stop="goToTerminal(server)"
              >
                终端
              </van-button>
              <van-button
                plain
                size="small"
                type="success"
                icon="chart-trending-o"
                @click.stop="goToMonitor(server)"
              >
                监控
              </van-button>
              <van-button
                plain
                size="small"
                type="default"
                icon="edit"
                @click.stop="editServer(server)"
              >
                编辑
              </van-button>
              <van-button
                plain
                size="small"
                type="danger"
                icon="delete-o"
                @click.stop="deleteServer(server)"
              >
                删除
              </van-button>
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>

    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTab" fixed placeholder>
      <van-tabbar-item icon="cluster-o" to="/servers">服务器</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>

    <!-- 添加/编辑服务器弹窗 -->
    <van-popup
      v-model:show="showAddDialog"
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="dialog-wrapper">
        <van-nav-bar
          :title="editingServer ? '编辑服务器' : '添加服务器'"
          left-text="取消"
          right-text="保存"
          @click-left="closeDialog"
          @click-right="saveServer"
        />
        <div class="dialog-content">
          <van-form ref="formRef">
            <van-cell-group inset>
              <van-field
                v-model="serverForm.name"
                label="名称"
                placeholder="服务器名称"
                :rules="[{ required: true, message: '请输入服务器名称' }]"
              />
              <van-field
                v-model="serverForm.host"
                label="主机"
                placeholder="IP地址或域名"
                :rules="[{ required: true, message: '请输入主机地址' }]"
              />
              <van-field
                v-model.number="serverForm.port"
                type="digit"
                label="端口"
                placeholder="SSH端口（默认22）"
              />
              <van-field
                v-model="serverForm.username"
                label="用户名"
                placeholder="SSH用户名"
                :rules="[{ required: true, message: '请输入用户名' }]"
              />
              <van-field
                v-model="serverForm.password"
                type="password"
                label="密码"
                placeholder="SSH密码"
              />
              <van-field
                v-model="serverForm.group_name"
                label="分组"
                placeholder="服务器分组（可选）"
              />
              <van-field
                v-model="serverForm.expire_date"
                label="到期时间"
                placeholder="选择到期时间"
                readonly
                is-link
                @click="showDatePicker = true"
              />
            </van-cell-group>
          </van-form>
        </div>
      </div>
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom" round>
      <van-date-picker
        v-model="currentDate"
        title="选择到期时间"
        :min-date="new Date()"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import serverAPI from '@/api/servers'

const router = useRouter()

// 状态
const activeTab = ref(0)
const loading = ref(false)
const refreshing = ref(false)
const servers = ref([])
const monitorData = ref({})
const showAddDialog = ref(false)
const showDatePicker = ref(false)
const editingServer = ref(null)
const formRef = ref(null)
const currentDate = ref(new Date())

// 表单数据
const serverForm = reactive({
  name: '',
  host: '',
  port: 22,
  username: '',
  password: '',
  group_name: '',
  expire_date: ''
})

// 计算属性
const expiringSoon = computed(() => {
  const now = new Date()
  const days7 = 7 * 24 * 60 * 60 * 1000
  return servers.value.filter(s => {
    if (!s.expire_date) return false
    const expireTime = new Date(s.expire_date).getTime()
    const diff = expireTime - now.getTime()
    return diff > 0 && diff <= days7
  }).length
})

// 加载服务器列表
const loadServers = async () => {
  try {
    loading.value = true
    console.log('📱 加载服务器列表')
    
    const response = await serverAPI.getAll()
    console.log('📦 服务器列表响应:', response)
    
    // 后端返回的数据结构：{ success: true, data: [...] }
    servers.value = response.data || []
    
    console.log('✅ 加载成功，共', servers.value.length, '台')
    console.log('📋 服务器列表:', servers.value)
    
    // 注意：监控数据通过WebSocket获取，列表页暂不显示
    // 可以在终端连接后通过WebSocket获取监控数据
  } catch (error) {
    console.error('❌ 加载失败:', error)
    showToast('加载服务器列表失败')
  } finally {
    loading.value = false
  }
}

// 注意：监控数据需要通过WebSocket获取
// 服务器列表页暂不显示监控数据，减少复杂度
// 监控数据请在监控页面查看

// 下拉刷新
const onRefresh = async () => {
  await loadServers()
  refreshing.value = false
  showToast({ message: '刷新成功', position: 'top' })
}

// 格式化到期时间
const formatExpireDate = (dateStr) => {
  if (!dateStr) return ''
  
  const expireDate = new Date(dateStr)
  const now = new Date()
  const diff = expireDate.getTime() - now.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days < 0) return '已到期'
  if (days === 0) return '今天到期'
  if (days <= 7) return `${days}天后到期`
  
  return `到期时间: ${expireDate.toLocaleDateString()}`
}

// 获取到期状态样式
const getExpireClass = (dateStr) => {
  if (!dateStr) return ''
  
  const expireDate = new Date(dateStr)
  const now = new Date()
  const diff = expireDate.getTime() - now.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days < 0) return 'expired'
  if (days <= 3) return 'danger'
  if (days <= 7) return 'warning'
  return 'normal'
}

// 跳转到终端
const goToTerminal = (server) => {
  console.log('📱 打开终端:', server.name)
  router.push(`/terminal/${server.id}`)
}

// 跳转到监控
const goToMonitor = (server) => {
  console.log('📱 打开监控:', server.name)
  router.push(`/monitor/${server.id}`)
}

// 编辑服务器
const editServer = (server) => {
  console.log('📝 编辑服务器:', server.name)
  editingServer.value = server
  Object.assign(serverForm, {
    name: server.name,
    host: server.host,
    port: server.port,
    username: server.username,
    password: '',
    group_name: server.group_name || '',
    expire_date: server.expire_date || ''
  })
  showAddDialog.value = true
}

// 删除服务器
const deleteServer = async (server) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除服务器 ${server.name} 吗？`
    })
    
    console.log('🗑️  删除服务器:', server.name)
    await serverAPI.delete(server.id)
    
    showToast({ type: 'success', message: '删除成功' })
    loadServers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('❌ 删除失败:', error)
      showToast('删除失败')
    }
  }
}

// 保存服务器
const saveServer = async () => {
  try {
    await formRef.value.validate()
    
    const data = { ...serverForm }
    
    if (editingServer.value) {
      console.log('💾 更新服务器:', data.name)
      await serverAPI.update(editingServer.value.id, data)
      showToast({ type: 'success', message: '更新成功' })
    } else {
      console.log('➕ 添加服务器:', data.name)
      await serverAPI.create(data)
      showToast({ type: 'success', message: '添加成功' })
    }
    
    closeDialog()
    loadServers()
  } catch (error) {
    console.error('❌ 保存失败:', error)
    if (error !== 'validation failed') {
      showToast('保存失败')
    }
  }
}

// 关闭对话框
const closeDialog = () => {
  showAddDialog.value = false
  editingServer.value = null
  Object.assign(serverForm, {
    name: '',
    host: '',
    port: 22,
    username: '',
    password: '',
    group_name: '',
    expire_date: ''
  })
}

// 日期确认
const onDateConfirm = (value) => {
  serverForm.expire_date = value.toISOString().split('T')[0]
  showDatePicker.value = false
}

// 页面加载
onMounted(() => {
  console.log('📱 服务器列表页加载')
  loadServers()
})
</script>

<style scoped>
.server-list-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 50px;
}

/* 内容区域 */
.content-wrapper {
  padding: 16px;
}

/* 统计卡片 */
.stats-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.3);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.stat-icon {
  font-size: 36px;
  color: rgba(255, 255, 255, 0.9);
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: white;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
}

.stat-divider {
  width: 1px;
  background: rgba(255, 255, 255, 0.3);
}

/* 服务器卡片 */
.server-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.server-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.server-card:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.server-info {
  flex: 1;
}

.server-name {
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin: 0 0 4px 0;
}

.server-host {
  font-size: 13px;
  color: #969799;
  margin: 0;
}

/* 服务器信息 */
.server-meta {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 12px;
  padding: 8px;
  background: #f7f8fa;
  border-radius: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #646566;
}

.meta-item .van-icon {
  color: #969799;
  font-size: 14px;
}

/* 到期信息 */
.expire-info {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 10px;
  border-radius: 6px;
  font-size: 12px;
  margin-bottom: 12px;
}

.expire-info.normal {
  background: #f0f9ff;
  color: #1989fa;
}

.expire-info.warning {
  background: #fff7e6;
  color: #ff976a;
}

.expire-info.danger {
  background: #ffebee;
  color: #ee0a24;
}

.expire-info.expired {
  background: #f5f5f5;
  color: #969799;
}

/* 卡片底部 */
.card-footer {
  display: flex;
  gap: 8px;
}

.card-footer .van-button {
  flex: 1;
  font-size: 12px;
}

/* 对话框 */
.dialog-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f7f8fa;
  color: #323233;
}

.dialog-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  color: #323233;
}

/* Vant样式覆盖 */
:deep(.van-nav-bar) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.van-nav-bar__title) {
  color: white;
  font-weight: bold;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-tabbar) {
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
}
</style>

